package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.utils.ObjectUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.dto.LikedTimesDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;
import static com.tianji.remark.constants.RedisConstants.LIKES_TIMES_KEY_PREFIX;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 */
@Service
@RequiredArgsConstructor
public class LikedRecordServiceRedisImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper mqHelper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        // 1.基于前端的参数，判断是执行点赞还是取消点赞
        boolean success = recordDTO.getLiked() ? like(recordDTO) : dislike(recordDTO);
        // 2.判断是否执行成功，如果失败，则直接结束
        if (!success) {
            return;
        }
        // 3.如果执行成功，统计点赞总数
        Long LikedTimes = redisTemplate.opsForSet().size(LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType());
        if (ObjectUtils.isEmpty(LikedTimes)) {
            return;
        }

        // 4.缓存点总数到Redis
        redisTemplate.opsForZSet().add(
                LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType(), recordDTO.getBizId().toString(), LikedTimes);


    }

    /**
     * @param bizIds
     * @Description 查询点赞总数
     * @Author 老李头儿
     * @Date 2025年03月31 20:24:30
     * @Return java.util.Set<java.lang.Long>
     **/

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        // 1.获取登录用户id
        Long userId = UserContext.getUser();

    // // 2.查询点赞状态
    //        List<Object> PipelineList = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
    //            StringRedisConnection stringConnection = (StringRedisConnection) connection;
    //            for (Long bizId : bizIds) {
    //                stringConnection.sIsMember(LIKES_TIMES_KEY_PREFIX + bizId, userId.toString());
    //            }
    //            return null;
    //        });
    //        //提取点赞过的业务id(bizid)
    //        Set<Long> Ids =new HashSet<>(bizIds.size());
    //        for (int i = 0; i < PipelineList.size(); i++) {
    //            Boolean o = (Boolean)PipelineList.get(i);
    //            if (o){
    //                Ids.add(bizIds.get(i));
    //            }
    //        }
    //
    //        return Ids;
        // 2. 查询点赞状态
        List<Object> likeStatusList = redisTemplate.executePipelined((RedisCallback<Boolean>) connection -> {
            StringRedisConnection stringConnection = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                stringConnection.sIsMember(LIKES_TIMES_KEY_PREFIX + bizId, userId.toString());
            }
            return null;
        });

        // 提取点赞过的业务id(bizid)
        Set<Long> likedIds = IntStream.range(0, likeStatusList.size())
                .filter(index -> (boolean) likeStatusList.get(index))
                .mapToObj(index -> bizIds.get(index))
                .collect(Collectors.toSet());

        return likedIds;
    }

    /**
    * @Description 定时处理点赞任务
    * @Author 老李头儿
    * @Date 2025年04月01 10:45:48
    * @param bizType
    * @param maxBizSize
    * @Return void
    **/

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        // 1.批量读取并移除Redis中缓存的点赞总数
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet()
                .popMin(LIKES_TIMES_KEY_PREFIX + bizType, maxBizSize);


        // 2.遍历元组并进行数据转换
        while (ObjectUtils.isNotEmpty(typedTuples)) {
            List<LikedTimesDTO> messages = new ArrayList<>(typedTuples.size());
            for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
                String bizId = typedTuple.getValue();
                Integer likedTimes = typedTuple.getScore().intValue();
                if (ObjectUtils.isNull(likedTimes) || ObjectUtils.isNull(bizId)) {
                    LikedTimesDTO message = LikedTimesDTO.of(Long.valueOf(bizId), likedTimes);
                    messages.add(message);
                }
            }
            // 3.发送MQ消息
            if (ObjectUtils.isNotEmpty(messages)) {
                mqHelper.send(
                        LIKE_RECORD_EXCHANGE,
                        StringUtils.format(LIKED_TIMES_KEY_TEMPLATE, bizType),
                        messages);
            }

            //继续查
            typedTuples = redisTemplate.opsForZSet().popMin(LIKES_TIMES_KEY_PREFIX + bizType, maxBizSize);
        }

    }

    /**
     * @param recordDTO
     * @Description 取消点赞
     * @Author 老李头儿
     * @Date 2025年03月31 20:27:55
     * @Return boolean
     **/

    private boolean dislike(LikeRecordFormDTO recordDTO) {
        // 1.获取用户id
        Long userId = UserContext.getUser();

        // 2.获取Key
        String key = LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType() + ":" + recordDTO.getBizId();

        // 3.执行SREM命令
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());

        return result != null && result > 0;
    }

    /**
     * @param recordDTO
     * @Description 点赞
     * @Author 老李头儿
     * @Date 2025年03月31 20:27:55
     * @Return boolean
     **/
    private boolean like(LikeRecordFormDTO recordDTO) {
        // 1.获取用户id
        Long userId = UserContext.getUser();

        // 2.获取Key
        String key = LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType() + ":" + recordDTO.getBizId();

        // 3.执行SADD命令
        Long result = redisTemplate.opsForSet().add(key, userId.toString());

        return result != null && result > 0;
    }
}